# -*- coding: utf-8 -*-
from django.contrib.syndication.views import Feed
from models import NewsItem
from urllib import urlopen
from google.appengine.api import memcache
import logging


class AllFeeds(Feed):
	title = '北京邮电大学新闻RSS'
	link = "http://www.bupt.edu.cn/"
	description = '北邮新闻(办公布告栏 学生布告栏 学校主页新闻)'
	author_name = 'jing@BUPT'

	def getItemsWithMemcahe(self, obj):
		if obj == 'all':
			items = memcache.get('all_items')
			if items is not None:
				return items
			else:
				items = NewsItem.all().order('-date').fetch(20)
				if not memcache.add('all_items', items, 500):
					logging.error("Memcache set failed.")
				return items
		elif obj:
			items = memcache.get(obj+'_items')
			if items is not None:
				return items
			else:
				items = NewsItem.all().filter('site = ', obj).order('-date').fetch(20)
				if not memcache.add(obj+'_items', items, 500):
					logging.error("Memcache set failed.")
				return items
		else:
			return None


	def get_object(self, request, site):
		if site == 'office':
			return u'办公布告栏'
		elif site == 'students':
			return u'学生布告栏'
		elif site == 'home':
			return u'主页新闻'
		elif site == 'all':
			return 'all'
		else:
			return None

	def items(self, obj):
		return self.getItemsWithMemcahe(obj)

	def item_title(self, item):
		return  '[' + item.site + '] ' + item.title

	def item_description(self, item):
		return item.description

	def item_link(self, item):
		return item.link

	def item_author_name(self, item):
		return item.publisher

	def item_categories(self, item):
		return item.category

	def item_pubdate(self, item):
		return item.date
